package com.huiyeji.dynamic.core.bean;

import com.huiyeji.dynamic.core.DynamicContext;
import com.huiyeji.dynamic.core.DynamicStatement;
import com.huiyeji.dynamic.core.DynamicStatementPointer;
import com.huiyeji.dynamic.core.annotations.DynamicBean;

import java.util.List;

@Deprecated
@DynamicBean("async")
public class DynamicAsync {

    private final DynamicContext context;

    private final DynamicStatementPointer asyncPointer;

    private final String asyncName;

    private int startIndex;

    private int endIndex;

    public DynamicAsync(DynamicContext context){
        this.context = context;

        DynamicStatementPointer pointer = context.getPointer();
        List<DynamicStatement> statements = pointer.getStatements();
        DynamicStatement curStatement = statements.get(pointer.getCurrentPosition());
        asyncName = curStatement.getDynamicResultName();
        if (asyncName == null || "".equals(asyncName)){
            throw new RuntimeException("Dynamic Async Result Name Not Found");
        }
        for (int i = pointer.getCurrentPosition() + 1; i < statements.size(); i++) {
            DynamicStatement statement = statements.get(i);
            if (asyncName.equals(statement.getDynamicObjectName())){
                if ("start".equals(statement.getDynamicMethodName())){
                    startIndex = i;
                } else if ("end".equals(statement.getDynamicMethodName())) {
                    endIndex = i;
                    break;
                }
            }
        }

        if (startIndex == 0 || startIndex >= endIndex){
            throw new RuntimeException("Dynamic Async Internal Sort Error");
        }

        asyncPointer = new DynamicStatementPointer(statements.subList(startIndex + 1,endIndex));
    }

    public void start(){
        context.removeObject(asyncName);
        context.getFactory().removeDynamicObject(asyncName);
        context.getPointer().setNextPosition(endIndex + 1);
        new Thread(() -> {
            while (asyncPointer.hasNext()){
                context.getExecutor().execute(context,asyncPointer.next());
            }
        }).start();
    }

    public void end(){

    }
}
